package com.example.springbootest.aspect;

import com.example.springbootest.annotation.Log;
import com.example.springbootest.entity.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author shiguorang
 * @version 1.0.0
 * @ClassName LogAspect
 * @Description TODO
 * @createTime 2022年08月09日 15:53:00
 */
@Aspect
@Component
@Slf4j
public class LogAspect {


    /**
     * 切入点
     */
    @Pointcut("@annotation(com.example.springbootest.annotation.Log)")
    public void logPointCut(){
    }

    /**
     * 前置通知
     * @param joinPoint
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doAfter(JoinPoint joinPoint){
        handleLog(joinPoint, null);
    }

    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, Exception e){

    }


    private void handleLog(JoinPoint joinPoint,Exception e){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = new SystemLog();
        String functionName  = signature.getDeclaringTypeName() + "." + signature.getName() + "()";
        Log annotation  = signature.getMethod().getAnnotation(Log.class);
        if (annotation != null){
            log.info(annotation.toString());
            log.info(functionName);
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private static Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }



}
